// src/router/permission.js
import router from "./index";
import LayoutContainerThree from "@/views/LayoutContainerThree.vue";
// import { useUserStore } from "@/stores/user";
// const userStore = useUserStore();
function filterRoutesByPermissions(routes, permissions) {
  return routes.filter((route) => {
    return route.permissions.some((permission) =>
      permissions.includes(permission)
    );
  });
}
// console.log(router, "dsadasde8quwe8qdhsaudhu");

function transformRoutes(backendRoutes) {
  console.log(backendRoutes, "backendRoutes111");
  const aa = filterRoutesByPermissions(backendRoutes, ["admin"]);
  console.log(aa, "aa");
  // userStore.setMenu(aa);
  const modules = import.meta.glob("../views/*.vue");
  console.log(modules, "modules");

  return aa.map((route) => {
    console.log(route.component, "route.component");
    if (route.component) {
      route.component = modules[`../views/${route.component}.vue`];
      console.log(route.component, "route.component");
    }

    const transformedRoute = {
      path: route.path,
      component: route.component,
      permissions: route.permissions,
    };

    // 如果有子路由，递归处理
    // if (route.children && route.children.length > 0) {
    //   transformedRoute.children = transformRoutes(route.children);
    // }
    console.log(transformedRoute, "transformedRoute");

    return transformedRoute;
  });
}

export function addDynamicRoutes(backendRoutes) {
  // 转换路由格式
  const transformedRoutes = transformRoutes(backendRoutes);
  console.log(transformedRoutes, "transformedRoutes");
  router.addRoute({
    path: "/",
    name: "LayoutContainer",
    component: LayoutContainerThree,
    redirect: "/home",
    children: transformedRoutes,
  });
}
